﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chowpoo.Diagnose;
using CourseSystem.Common.Helpers;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;
using log4net;

namespace CourseSystem.Stat
{
    public class UrlStatThread : ThreadDiagnosable
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(UrlStatThread));

        public UrlStatThread(TimeSpan relaxTimeout, TimeSpan dozeTimeout)
            : base(relaxTimeout, dozeTimeout)
        {
        }

        protected override bool RelaxAfterExecution()
        {
            try
            {
                //处理学生
                for (var i = 0; i < UrlStat.StudentUrlStatDic.Count; i++)
                {
                    var item = UrlStat.StudentUrlStatDic.ElementAt(i);
                    //无活动2分钟
                    if (item.Value.LastUpdateTime.AddMinutes(2).CompareTo(DateTime.Now) < 0)
                    {
                        //更新数据库
                        UrlStat.UrlChangeSubmit(item.Value, true);
                        UrlStat.UpdateLastUrl(item.Value.Id, item.Value.Url);
                        StudentBLL.SetLogout(item.Value.Id);
                        //统计学习进程
                        LearnProcessStat.UpdateUser(item.Value.Id);
                    }
                }
                //处理教师
                for (var i = 0; i < UrlStat.TeacherUrlStatDic.Count; i++)
                {
                    var item = UrlStat.TeacherUrlStatDic.ElementAt(i);
                    //无活动2分钟
                    if (item.Value.LastUpdateTime.AddMinutes(2).CompareTo(DateTime.Now) < 0)
                    {
                        //更新数据库
                        UrlStat.UrlChangeSubmit(item.Value, true);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("Url统计出错!", ex);
                return false;
            }
        }
    }
}
